import React from 'react';
import { Select, Spin, message } from 'antd';
import { getRes } from '../../configFile';
import UserInfo from '../../types/UserInfo';

//该组件不能通用于所有输入选择框，由于渲染的Option不能确定key,value,children的名称,date类型需要手动更改

const { Option } = Select;

interface IProps {
    queryFunc: (keyword: string) => any //输入变化后调用的函数
    onChange?: (value: string) => void
    value?: number
}

interface IState {
    data: Array<UserInfo>
    inputValue: string   //输入值
    isFetching: boolean  //是否正在选择
}
export default class DeviceAdminForDevice extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            data: [],
            inputValue: '',
            isFetching: false,
        };
    }

    triggerChange = (changedValue: string) => {
        if (this.props.onChange) {
            this.props.onChange(changedValue);
        }
    };

    fetchUser = async (value: string) => {
        this.setState({ data: [] });
        if (!!value) {
            try {
                const res = getRes(await this.props.queryFunc(value))
                if (res.isSuccessful === false) {
                    message.error(res.message)
                } else {
                    this.setState({ data: res.data })
                }
            } catch (err) {
                message.error(err.toString());
            }
        }
    };

    handleChange = (value: string) => {
        console.log("handleChange", value)
        this.setState({
            inputValue: value,
            data: [],
            isFetching: false,
        });
        this.triggerChange(value)
    };

    render() {
        const { isFetching, data, inputValue } = this.state;
        return (
            <Select
                showSearch
                value={this.props.value ? this.props.value.toString() : inputValue}
                placeholder="Select users"
                notFoundContent={isFetching ? <Spin size="small" /> : null}
                filterOption={false}
                onSearch={this.fetchUser}
                onChange={this.handleChange}
                style={{ width: '100%' }}
            >
                {data.map(d => (
                    <Option value={d.ID} key={d.ID}>{d.username}</Option>
                ))}
            </Select>
        );
    }
}
